import tkinter as tk
from tkinter import Toplevel, StringVar, IntVar, BooleanVar, messagebox
import ttkbootstrap as ttk
from ttkbootstrap import Treeview
from ttkbootstrap.constants import *
from data.Database import Subject


class SubjectTree(ttk.Frame):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.tree = ttk.Treeview(self, columns=('科目名称', '科目简称', '科目总分', '监测状态'))
        self.tree.heading('#0', text='编号')
        self.tree.heading('#1', text='科目名称')
        self.tree.heading('#2', text='科目简称')
        self.tree.heading('#3', text='科目总分')
        self.tree.heading('#4', text='是否赋分')
        self.tree.column('#0', anchor=CENTER, width=100)
        self.tree.column('#1', anchor=CENTER, width=100)
        self.tree.column('#2', anchor=CENTER, width=100)
        self.tree.column('#3', anchor=CENTER, width=100)
        self.tree.column('#4', anchor=CENTER, width=100)
        self.tree.pack(side='top', fill=BOTH, expand=True)
        btn_frame = ttk.Frame(self)
        btn_frame.pack(side='bottom', anchor=CENTER)
        ttk.Button(btn_frame, text="添加", command=self.add_item).pack(side='right', anchor=CENTER, padx=3, pady=4)
        ttk.Button(btn_frame, text="删除", command=self.delete_item).pack(side='right', anchor=CENTER, padx=3, pady=4)
        ttk.Button(btn_frame, text="修改", command=self.change_item).pack(side='right', anchor=CENTER, padx=3, pady=4)
        # 读取设置内容
        self.model = Subject()
        self.init_data()

    def init_data(self):
        self.tree.delete(*self.tree.get_children())
        subjects = self.model.all()
        for item in subjects:
            # print(item.title)
            self.tree.insert("", index=END, text=item[0], values=(item.title, item.jc, item.mf, item.state))

    def item_view(self, ids=None, title=None, jc=None, mf=None, state=False):
        tl = tk.Toplevel(self)
        tl.title("添加科目")
        tl.transient()
        tl.geometry("350x500+{}+{}".format(self.winfo_rootx(), self.winfo_rooty()))
        title = StringVar(value=title)
        jc = StringVar(value=jc)
        mf = IntVar(value=mf)
        state = BooleanVar(value=state)

        def proceed():
            if title.get() and jc.get() and mf.get():
                if not jc.get().isascii():
                    messagebox.showerror("简称错误！", "简称只能包含数字、字母！")
                    return
                if ids is not None:
                    self.model.update(ids, title.get(), jc.get(), mf.get(), state.get())
                else:
                    self.model.create(title.get(), jc.get(), mf.get(), state.get())
            else:
                messagebox.showerror("填写错误！", "表格的前三项是必填项目！")
                return
            self.init_data()
            tl.destroy()

        fr = ttk.Frame(tl)
        fr.pack(fill=BOTH, expand=True, padx=20)

        ttk.Label(fr, text='添加新的科目', font=("微软雅黑", 30, "bold"), anchor=CENTER).pack(side=TOP, pady=10, fill=BOTH, expand=True)
        ttk.Label(fr, text="科目名称: ").pack(side=TOP, pady=10, anchor=W, fill=X, expand=True)
        ttk.Entry(fr, textvariable=title).pack(side=TOP, pady=5, anchor=W, fill=X, expand=True)
        ttk.Label(fr, text="科目简称(只能包含字母、数字): ").pack(side=TOP, pady=10, anchor=W, fill=X, expand=True)
        ttk.Entry(fr, textvariable=jc).pack(side=TOP, pady=5, anchor=W, fill=X, expand=True)
        ttk.Label(fr, text="科目满分: ").pack(side=TOP, pady=10, anchor=W, fill=X, expand=True)
        ttk.Spinbox(fr, from_=0, to=200, textvariable=mf).pack(side=TOP, pady=5, anchor=W, fill=X, expand=True)
        ttk.Label(fr, text="是否赋分: ").pack(side=TOP, pady=10, anchor=W, fill=X, expand=True)
        ttk.Checkbutton(fr, variable=state, state=tk.DISABLED).pack(side=TOP, pady=5, padx=5, anchor=W, fill=X, expand=True)
        ttk.Button(fr, text="确认", width=20, command=proceed).pack(side=TOP, pady=10, anchor=W, fill=X, expand=True)

    def add_item(self):
        self.item_view()

    def delete_item(self):
        index = self.tree.focus()
        pr = self.tree.item(index, 'text')
        jc = self.tree.item(index, 'value')[1]
        if index:
            if messagebox.askyesno('系统提示', f'您确认要删除简称为 {jc} 该科目数据吗？'):
                self.tree.delete(index)
                self.model.delete(pr)

    def change_item(self):
        index = self.tree.focus()
        if index:
            ids = self.tree.item(index, 'text')
            values = self.tree.item(index, 'values')
            self.item_view(ids, *values)

    def validate_al_num(self, value: str):
        if value.isascii():
            return True
        else:
            messagebox.showerror("填写错误！", "简写只能是字母或者数字！")
            return False


